package com.chookss.view;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.update.UpdateService;
import com.chookss.tools.AppUtil;
import com.chookss.tools.MyToast;
import com.chookss.tools.Utils;
import com.chookss.view.listener.ShareDialogListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;

import butterknife.BindView;

import static com.lzy.okgo.utils.HttpUtils.runOnUiThread;


public class UpdateDialog extends BaseDialog {
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tvContent)
    TextView tvContent;
    @BindView(R.id.tvCancel)
    TextView tvCancel;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.progressbarDown)
    ProgressBar progressbarDown;
    @BindView(R.id.tvProcess)
    TextView tvProcess;
    @BindView(R.id.llProgress)
    LinearLayout llProgress;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    private Context context;
    private String updateFlag = "0", downUrl = "";
    private ShareDialogListener listener = null;

    public UpdateDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_update;
    }

    @Override
    protected void init(View view) {
        initCenter(0.3f);
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(updateFlag)) {
                    llBottom.setVisibility(View.GONE);
                    llProgress.setVisibility(View.VISIBLE);
                    downloadApk();
                } else {
                    if(Utils.isNull(downUrl)||context==null){
                        MyToast.show("下载异常，请稍后重试");
                        return;
                    }
                    Intent intent = new Intent(context, UpdateService.class);
                    intent.putExtra("url", downUrl);
                    context.startService(intent);
                    dismiss();
                }

            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    public UpdateDialog(@NonNull Context context, String versionName, String versionDesc, String flag, String url, ShareDialogListener listener) {
        super(context);
        this.context = context;
        this.updateFlag = flag;
        this.listener = listener;
        this.downUrl = url;
        tvVersion.setText(versionName + "版本全新上线");
        tvContent.setText(Html.fromHtml(versionDesc));
        if ("1".equals(updateFlag)) {
            //强制升级
            //        ；即可实现点击外部不消失
            setCanceledOnTouchOutside(false);
            setCancelable(false);
            tvCancel.setVisibility(View.GONE);
        }
    }

    /**
     * 下载apk
     */
    public void downloadApk() {
        String fileName = downUrl.substring(downUrl.lastIndexOf("/") + 1);
        File appDir = context.getExternalFilesDir(Urls.APKFOLDER);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        if (AppUtil.getRootDirectory() < 100) {
            MyToast.show("存储空间不足");
            return;
        }
        OkGo.<File>get(downUrl).execute(new FileCallback(appDir.getAbsolutePath(), fileName) {
            int currentPercent = 0;
            @Override
            public void downloadProgress(Progress progress) {

                currentPercent = (int) (progress.fraction * 100);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (null != tvProcess) tvProcess.setText("已下载 " + currentPercent + "%");
                        if (null != progressbarDown) progressbarDown.setProgress(currentPercent);
                    }
                });
            }

            @Override
            public void onError(Response<File> response) {
                MyToast.show("下载更新文件失败");
                dismiss();
                currentPercent = 0;
            }

            @Override
            public void onSuccess(Response<File> response) {
                if (listener != null) {
                    listener.onClick();
                }
                currentPercent = 0;
                dismiss();

            }
        });
    }

}